import {
	getTopicMaterialPage,
	type IMaterialInfoResponse,
	type IMaterialListParams
} from '@/api/marterial';
import { chooseMaterials } from '@/api/myResearch';
import { MaterialItem } from '@/components';
import { useRequest } from '@ac/hooks';
import { AppPagination, EmptyState } from '@ac/ui-components';
import { Button, Flex, message, Spin } from 'antd';
import to from 'await-to-js';
import { useCallback, useEffect, useMemo } from 'react';
import { useImmer } from 'use-immer';
import ChooseMaterialModal from '../Dialog/ChooseMaterialDialog';
import SearchForm from './SearchForm';

type MaterialQueryInfo = {
	visible: boolean;
	total: number;
	materials: IMaterialInfoResponse[];
	queryInfo: IMaterialListParams;
};

type SearchFormValues = Pick<IMaterialListParams, 'titleKey' | 'tagKey'>;

const useMaterialAction = (id: string) => {
	const [state, setState] = useImmer<MaterialQueryInfo>({
		visible: false,
		total: 0,
		materials: [],
		queryInfo: {
			id,
			titleKey: '',
			tagKey: '',
			pageSize: 10,
			pageNum: 1
		}
	});

	/**
	 * 打开添加素材弹窗
	 */
	const openModal = useCallback(() => {
		setState(state => {
			state.visible = true;
		});
	}, [setState]);

	/**
	 * 关闭添加素材弹窗
	 */
	const closeModal = useCallback(() => {
		setState(state => {
			state.visible = false;
		});
	}, [setState]);

	// 分页查询素材列表
	const { loading, run: fetchMaterialPage } = useRequest(
		useCallback(
			async (params: IMaterialListParams) => {
				const [_err, res] = await to(getTopicMaterialPage(params));
				if (res) {
					setState(state => {
						state.materials = res.result || [];
						state.total = res.pageinfo?.pagecount || 0;
					});
				}
			},
			[setState]
		)
	);

	/**
	 * 分页变化处理
	 * @param pageNum - 页码
	 * @param pageSize - 每页大小
	 */
	const handlePaginationChange = useCallback(
		(pageNum: number, pageSize: number) => {
			setState(state => {
				state.queryInfo = { ...state.queryInfo, pageNum, pageSize };
			});
		},
		[setState]
	);

	// 更新查询参数
	const updateState = useCallback(
		(values: SearchFormValues) => {
			setState(state => {
				state.queryInfo = { ...state.queryInfo, ...values, pageNum: 1 };
			});
		},
		[setState]
	);

	// 提交选择素材
	const chooseSubmit = useCallback(
		async (values: { materialList: string[] }) => {
			const [_err, res] = await to(
				chooseMaterials({
					id,
					materialList: values.materialList
				})
			);
			if (res) {
				message.success('保存成功');
				setState(state => {
					state.visible = false;
					state.queryInfo.pageNum = 1;
				});
				fetchMaterialPage(state.queryInfo);
			}
		},
		[state.queryInfo, setState, id, fetchMaterialPage]
	);

	useEffect(() => {
		fetchMaterialPage(state.queryInfo);
	}, [state.queryInfo, fetchMaterialPage]);

	return {
		state,
		loading,
		actions: {
			handlePaginationChange,
			updateState,
			openModal,
			closeModal,
			chooseSubmit
		}
	};
};

type MaterialListsProps = {
	total: MaterialQueryInfo['total'];
	queryInfo: MaterialQueryInfo['queryInfo'];
	materials: MaterialQueryInfo['materials'];
	openModal: () => void;
	updateState: (values: SearchFormValues) => void;
	handlePaginationChange: (pageNum: number, pageSize: number) => void;
};

const MaterialDataList: React.FC<MaterialListsProps> = ({
	total = 0,
	queryInfo,
	materials = [],
	openModal,
	updateState,
	handlePaginationChange
}) => {
	return (
		<div className="h-full flex flex-col">
			<SearchForm onSearch={updateState}>
				<Button onClick={openModal} type="primary">
					添加素材
				</Button>
			</SearchForm>
			{materials.length > 0 ? (
				<Flex vertical gap={10} className="flex-1 h-0 overflow-auto">
					{/* 素材列表 */}
					{materials?.map(item => (
						<MaterialItem key={item.doc_id} material={item} showDelete={false} />
					))}
				</Flex>
			) : (
				<EmptyState className="mt-80" showBtn={false} description="搜索结果为空" />
			)}
			{total > 0 && (
				<AppPagination
					current={queryInfo.pageNum}
					pageSize={queryInfo.pageSize}
					total={total}
					onChange={handlePaginationChange}
				/>
			)}
		</div>
	);
};

const MaterialLists: React.FC<{ id: string }> = ({ id }) => {
	const { state, loading, actions } = useMaterialAction(id);
	const { handlePaginationChange, updateState, openModal, closeModal, chooseSubmit } = actions;

	// 空状态判断
	const isInitialEmpty = useMemo(() => {
		const isNoMaterial = !state.materials || state.materials.length === 0;
		const notSearching = !state.queryInfo.titleKey && !state.queryInfo.tagKey;
		return !loading && isNoMaterial && notSearching;
	}, [state.materials, loading, state.queryInfo.titleKey, state.queryInfo.tagKey]);

	if (isInitialEmpty) {
		return (
			<>
				<EmptyState
					className="mt-80"
					btnText="添加研究素材"
					description="该选题下暂无研究素材，点击可添加素材~"
					onCreate={openModal}
				/>
				<ChooseMaterialModal visible={state.visible} onCancel={closeModal} onOk={chooseSubmit} />
			</>
		);
	}

	return (
		<>
			{loading ? (
				<div className="h-full flex items-center justify-center">
					<Spin />
				</div>
			) : (
				<MaterialDataList
					total={state.total}
					updateState={updateState}
					openModal={openModal}
					queryInfo={state.queryInfo}
					materials={state.materials}
					handlePaginationChange={handlePaginationChange}
				/>
			)}

			<ChooseMaterialModal visible={state.visible} onCancel={closeModal} onOk={chooseSubmit} />
		</>
	);
};

export default MaterialLists;
